<?php
class Cache {
	protected $cfg;
	protected $caches = array();
	
	public function __construct($cfg) {
		$this->setCfg($cfg);
		$this->setCaches();
	}
	
	public function store($key, $val) {
		$ret = false;
		foreach($this->caches as $cache) {
			//只要有一个保存成功了，就认为是成功了
			if(!$ret && $cache->store($key, $val)) $ret = true;
		}
		return $ret;
	}
	
	public function fetch($key) {
		foreach($this->caches as $cache) {
			if($ret = $cache->fetch($key)) return $ret;
		}
		
		return null;
	}
	
	public function delete($key) {
		foreach($this->caches as $cache) {
			//需要全部删除成功，则认为是成功的
			if(!$cache->delete($key)) return false;
		}
		
		return true;
	}
	
	public function clear() {
		foreach($this->caches as $cache) {
			//需要全部清除成功，则认为是成功的
			if(!$cache->clear()) return false;
		}
		
		return true;
	}
	
	public function dump() {
		foreach($this->caches as $cache) {
			$cache->dump();
		}
	}
	
	protected function setCaches() {
		foreach($this->cfg['caches'] as $cache) {
			$clzFile = FRAMEWORK_CACHE_ROOT . "drivers/{$cache}.class.php";
			if(file_exists($clzFile)) require_once $clzFile;
			$this->caches[] = new $cache ($this->cfg);
		}
	}
	
	protected function setCfg($cfg) {
		$this->cfg = require FRAMEWORK_CACHE_ROOT . 'config.php';
		foreach($cfg as $k => $v) {
			if(array_key_exists($k, $this->cfg)) $this->cfg[$k] = $v;
		}
	}
}
?>